/**
 * @api post controller.
 *
 * User: yunshengzhu
 * Date: 2019-04-09
 * Time: 14:18
 */
package control

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mingzhehao/goutils/filetool"
	"math"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"pkg/cfg"
	"strconv"
	"strings"
	"time"
)

var uploadAddressCdn string
var cdnSwitch bool

var showAddressCdn string = "http://127.0.0.1:8099"

func InitCdn(sch bool, showAddress, uploadAddress string) {
	cdnSwitch = sch
	uploadAddressCdn = uploadAddress
	showAddressCdn = showAddress
	cfg.LogInfo("cdn 加载成功:", cdnSwitch, showAddressCdn, uploadAddressCdn)
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		fmt.Println(err)
	}
	return strings.Replace(dir, "\\", "/", 0)
}

func GetCookieKey() string {
	return "backstage_token"
}

var noCheckMap map[string]bool

func GetKeyInt64(c *gin.Context, key string, def ...int64) int64 {
	v := c.Query(key)
	if len(v) <= 0 {
		if len(def) > 0 {
			return def[0]
		}
		return 0
	}
	val, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		cfg.LogErr("err:", err, v)
	}
	return val
}

func GetPostForm(c *gin.Context, key string) int64 {
	v := c.PostForm(key)
	if len(v) <= 0 {
		return 0
	}
	val, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		cfg.LogErr("err:", err, v)
	}
	return val
}

func SuccessJson(c *gin.Context, code int64, msg string, out interface{}) {
	data := make(map[string]interface{})
	data["code"] = code
	if msg == "登录已过期" {
		data["code"] = -2
	}
	data["msg"] = msg
	data["data"] = out

	outData, err := json.Marshal(data)
	if err != nil {
		cfg.LogErr("err:", err)
	}

	cfg.LogInfof("out:%s", string(outData))

	c.JSON(200, data)
}

func Success(c *gin.Context, msg string, url string, wait int) {
	data := make(map[string]interface{})
	data["type"] = true
	data["title"] = "message"
	data["msg"] = msg
	data["wait"] = wait
	if url == "-1" {
		url = c.Request.Referer()
	} else if url == "-2" {
		url = c.Request.Referer()
	}
	data["url"] = url
	c.HTML(http.StatusOK, "mes.tpl", gin.H{
		"mess": data,
	})
}

/*
* 失败跳转
 */
func Error(c *gin.Context, msg string, url string, wait int) {
	data := make(map[string]interface{})
	data["type"] = false
	data["title"] = "error message"
	data["msg"] = msg
	data["wait"] = wait
	if url == "-1" {
		url = c.Request.Referer()
	} else if url == "-2" {
		url = c.Request.Referer()
	}

	data["url"] = url
	c.HTML(http.StatusOK, "mes.tpl", gin.H{
		"mess": data,
	})
}

func CreatePaging(page, pageSize, total int64) *Paging {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	pageCount := math.Ceil(float64(total) / float64(pageSize))
	paging := new(Paging)
	paging.Page = page
	paging.PageSize = pageSize
	paging.Total = total
	paging.PageCount = int64(pageCount)
	paging.NumsCount = 10
	paging.setNums()
	return paging
}

type Paging struct {
	Page      int64   //当前页
	PageSize  int64   //每页条数
	Total     int64   //总条数
	PageCount int64   //总页数
	Nums      []int64 //分页序数
	NumsCount int64   //总页序数
}

func (this *Paging) setNums() {
	this.Nums = []int64{}
	if this.PageCount == 0 {
		return
	}
	half := math.Floor(float64(this.NumsCount) / float64(2))
	begin := this.Page - int64(half)
	if begin < 1 {
		begin = 1
	}
	end := begin + this.NumsCount - 1
	if end >= this.PageCount {
		begin = this.PageCount - this.NumsCount + 1
		if begin < 1 {
			begin = 1
		}
		end = this.PageCount
	}
	for i := begin; i <= end; i++ {
		this.Nums = append(this.Nums, i)
	}
}

func getRand(n int) string {
	rand.Seed(int64(time.Now().Nanosecond()))
	var str string
	for i := 0; i < n; i++ {
		str = str + fmt.Sprintf("%d", rand.Intn(9))
	}
	return str
}

const LOCAL_FILE_DIR = "/upload"

func uploadImgMultiple(c *gin.Context, upName string) (path []string, err error) {
	form, err := c.MultipartForm()
	if err != nil {
		cfg.LogErr("err:", err)
		return path, err
	}
	files := form.File[fmt.Sprintf("%s[]", upName)]
	for _, file := range files {
		filename := file.Filename
		ext := filetool.Ext(filename)
		imgPath := getPathImg(ext)
		err := c.SaveUploadedFile(file, imgPath)
		if err != nil {
			cfg.LogErr("err:", err)
			return path, err
		}
		path = append(path, imgPath)
	}
	return path, nil
}

func getPathImg(ext string) string {
	name := time.Now().Format("20060102150405")
	fileSaveName := fmt.Sprintf("%s_%s%s", name, getRand(10), ext)
	imgPath := fmt.Sprintf("%s/%s/%s", LOCAL_FILE_DIR, time.Now().Format("200601"), fileSaveName)
	filetool.InsureDir(getCurrentDirectory() + "/" + LOCAL_FILE_DIR + "/" + time.Now().Format("200601"))
	return imgPath
}

func uploadImg(c *gin.Context, name string) (path string, err error) {
	f, h, err := c.Request.FormFile(name)
	if err != nil {
		if err.Error() != "http: no such file" {
			cfg.LogErr("上传图片失败:", err)
			return "", err
		}
		return "", nil
	} else {
		defer f.Close()
		ext := filetool.Ext(h.Filename)
		imgPath := getPathImg(ext)
		err := c.SaveUploadedFile(h, getCurrentDirectory()+imgPath)
		if err != nil {
			cfg.LogErr("err:", err)
			return "", err
		}
		return imgPath, nil
	}
}